﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Apollo;
using System.Web.Security;
using NHibernate;

namespace Apollo.Website
{
    public partial class Controls_UserImpersonate : System.Web.UI.UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.Page.IsPostBack)
            {
                DropDownListUsers.Visible = false;
                DropDownListUsers.DataTextField = "Name";
                DropDownListUsers.DataValueField = "Name";

                IUser u = this.Page.User.Identity as IUser;

                if (u.Role != null && u.Role.Name == Role.ADMIN_ROLE)
                {
                    DropDownListUsers.Visible = true;
                    DropDownListUsers.DataSource = Apollo.Application.CurrentSession
                            .QueryOver<User>()
                            .Where(user => user.Id != u.Id)
                            .OrderBy(user => user.Name)
                            .Asc
                            .List();
                    DropDownListUsers.DataBind();
                }
            }
        }

        protected void DropDownListUsers_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (DropDownListUsers.SelectedValue == "")
            {
                Deimpersonate();
            }
            else if (DropDownListUsers.SelectedValue != "-")
            {
                // impersonate
                User user = Apollo.Application.CurrentSession.Get<User>((this.Page.User.Identity as IUser).Id);

                user.Impersonate = Apollo.Application.CurrentSession.QueryOver<User>()
                            .Where(u => u.Name == DropDownListUsers.SelectedValue)
                            .SingleOrDefault();

                ITransaction tran = Apollo.Application.CurrentSession.BeginTransaction();
                try
                {
                    Apollo.Application.CurrentSession.Save(user);

                    tran.Commit();
                }
                catch
                {
                    tran.Rollback();
                }
            }

            Response.Redirect("~/");
        }

        protected void Deimpersonate()
        {
            User user = Apollo.Application.CurrentSession.Get<User>((this.Page.User.Identity as IUser).Id);

            if (user.Impersonate == null)
                return;

            ITransaction tran = Apollo.Application.CurrentSession.BeginTransaction();
            try
            {
                user.Impersonate = null;

                Apollo.Application.CurrentSession.Save(user);

                tran.Commit();
            }
            catch
            {
                tran.Rollback();
            }

            Response.Redirect("~/");
        }
    }
}